package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import com.yunshipei.common.ProfileResHandler;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.ProxySettings;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.H5ContactModel;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.ui.view.H5ContactWebView;
import com.yunshipei.ui.view.SwipeLayout;
import com.yunshipei.ui.view.client.H5WebViewClient;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

public class H5ContactFragment extends H5BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String BUNDLE_H5_CONTACT_DATA = "bundle.h5.contact.data";

    public static H5ContactFragment newInstance(MainExtraBean mainExtraBean) {
        H5ContactFragment contactFragment = new H5ContactFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_H5_CONTACT_DATA, mainExtraBean);
        contactFragment.setArguments(bundle);
        return contactFragment;
    }

    @Bind(R.id.h5_web_view)
    protected H5ContactWebView mWebView;
    @Bind(R.id.h5_loading_view)
    protected RelativeLayout mLoadingView;
    @Bind(R.id.refresh_layout)
    protected SwipeLayout mRefreshLayout;

    private MainExtraBean mMainExtraBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainExtraBean = (MainExtraBean) getArguments().getSerializable(BUNDLE_H5_CONTACT_DATA);
    }

    @Override
    public void startProxy() {
        if (!TextUtils.isEmpty(mProxyIP) && 0 != mProxyPort) {
            ProxySettings.setProxy(mWebView, mProxyIP, mProxyPort);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_h5_contact, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setProgressViewOffset(false, 0, getResources().getDimensionPixelOffset(R.dimen.swep_refresh_position));
        mRefreshLayout.setColorSchemeColors(EnterConfig.getInstance().getGlobalColor());
        mRefreshLayout.setEnabled(false);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.addJavascriptInterface(redCore, "redcore");
        mWebView.setWebViewClient(new H5WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mLoadingView.getVisibility() == View.VISIBLE) {
                    mLoadingView.setVisibility(View.INVISIBLE);
                }
            }
        });
        Flowable.just(mMainExtraBean.getH5ContactModel()).flatMap(new Function<H5ContactModel, Publisher<String>>() {
            @Override
            public Publisher<String> apply(H5ContactModel h5ContactModel) throws Exception {
                ProfileResHandler profileResHandler = new ProfileResHandler(mContext, mManagerServer);
                return profileResHandler.contactsPageFlowable(h5ContactModel.getVersion(), h5ContactModel.getDownloadUrl());
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String url) throws Exception {
                startProxy();
                mWebView.loadUrl(url);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(throwable.getMessage() + ",将使用缓存资源");
                File file = new File(mContext.getFilesDir().getParent() + File.separator + "web_contacts" + File.separator + "index.html");
                startProxy();
                if (file.exists()) {
                    mWebView.loadUrl("file://" + file.getPath());
                } else {
                    mWebView.loadUrl("file:///android_asset/local/addressbookpage/index.html");
                }
            }
        });
    }

    private Object redCore = new Object() {

        @JavascriptInterface
        public String userInfo() {
            UserInfo userInfo = mMainExtraBean.getUserInfo();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("managerServer", EnterConfig.getInstance().getManagerServer());
                jsonObject.put("companyId", userInfo.getCompanyId());
                jsonObject.put("companyName", mMainExtraBean.getCompanyTitle());
                jsonObject.put("departmentId", userInfo.getDepartmentId());
                jsonObject.put("topId", mMainExtraBean.getTopId());
                jsonObject.put("departmentName", userInfo.getDepartment());
                jsonObject.put("userUuid", userInfo.getUuid());
                jsonObject.put("userName", userInfo.getName());
                jsonObject.put("themeColor", EnterConfig.getInstance().optGlobalColor());
            } catch (JSONException ignored) {
            }
            return jsonObject.toString();
        }

        @JavascriptInterface
        public void setCanDropDownRefresh(final boolean refresh) {
            AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
                @Override
                public void run() {
                    mRefreshLayout.setCanRefresh(refresh);
                    mRefreshLayout.isScrollTop(refresh);
                }
            });
        }

        @JavascriptInterface
        public void clientStopRefresh() {
            AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
                @Override
                public void run() {
                    mRefreshLayout.setRefreshing(false);
                    mRefreshLayout.isScrollTop(true);//刷新成功默认滑到顶
                }
            });
        }

        @JavascriptInterface
        public void startMessage(final String uuid) {
            RongIM.getInstance().startConversation(getActivity(), Conversation.ConversationType.PRIVATE, uuid, "");
        }

        @JavascriptInterface
        public void startGroupMessage(final String groupId) {
            RongIM.getInstance().startGroupChat(getActivity(), groupId, "");
        }

        @JavascriptInterface
        public void clientReceptionRefresh() {
            mRefreshLayout.isScrollTop(true);
        }
    };

    @Override
    public boolean pageCanGoBack() {
        return mWebView != null && mWebView.canGoBack();
    }

    @Override
    public void pageGoBack() {
        if (mWebView != null) {
            mWebView.goBack();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mWebView != null) {
            mWebView.destroy();
        }
    }

    @Override
    public void onRefresh() {
        mWebView.loadUrl("javascript:clientStartRefresh()");
    }
}
